#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include <sys/stat.h>
#include<dirent.h>
#include<fcntl.h>
#include<unistd.h> 
#include<pthread.h>

int ls(char* path);
bool flag_index = false;

int
main(int argc, char* args[])
{
	//printf("\nargc is %d\n",argc);
	if(argc == 1){
		flag_index = true;
		ls(".");
	}
	else if(argc !=2 ){
		perror("arguments error");
		exit(1);	
	}
	//char path[] = *args[1];
	else ls(args[1]);

	exit(0);
}

int ls(char* path)
{
	DIR* dp;
	printf("path is %s\n",path);
	dp = opendir(path);
	
	if(dp == NULL){
		printf("there\n");
		perror("open dir error");
		exit(1);
	}
	else printf("dp is not null\n");

	struct dirent* det;
	errno = 0;
	
	while(det = readdir(dp)){
		printf("No error in line 47\n");
		printf("file name is  %s\n",det->d_name);
		//file is dir,keep ls(file_name);
		if(det->d_type == DT_DIR) 
		{
			
			if(det->d_name == "..")
			continue;
			else if(det->d_name == "." && flag_index)
			continue;
			char* next_path;
			sprintf(next_path,"%s/%s", path, det->d_name);
			ls(next_path);
		}

		//file is not dir,show it's type name size
		else{
			struct stat stbuf;

			if((stat(path, &stbuf)) < 0){
				perror("get stat error");
				exit(1);
			}
			printf("line 66\n");
			//printf("file type:%s\n", det -> d_type);
			printf("file name:%s\n", det -> d_name);
			printf("line69\n");
			printf("file size:%d\n", stbuf.st_size);
			//printf("file type:%s\t file name:%s\t file size:%d\n",det->d_type,det->d_name,stbuf.st_size);
		}
	}

	if(errno){
			perror("read dir error");
			exit(1);
	}
	printf("line 79\n");
	return 0;
}
